import React, { useState } from "react";
import { View, Text, StyleSheet, TouchableOpacity, Alert } from "react-native";
import { AntDesign } from "@expo/vector-icons";
import * as FileSystem from "expo-file-system";
import * as Linking from "expo-linking";
import { fileWeb } from "../../api/query";
import * as Permissions from "expo-permissions";
import * as MediaLibrary from "expo-media-library";
import * as IntentLauncher from "expo-intent-launcher";
import LoadingBar from "../InterView/LoadingBar";
import { StorageAccessFramework } from "expo-file-system";

const ResearchCard = ({
  item,
  isDelete,
  deletedId,
  onDeleted,
  isExamine,
  onPass,
  onReject,
}) => {
  const [isLoading, setIsLoading] = useState(false);
  const [hasMediaLibraryPermission, setHasMediaLibraryPermission] = useState();
  let time = new Date(item.time);

  const onDownload = async () => {
    // try {

    //   //下载
    setIsLoading(true);
    let URL = fileWeb + "/" + item.fileObject.filePath;
    let LocalPath = FileSystem.documentDirectory + item.fileObject.fileName;
    // const downloadResumable = FileSystem.createDownloadResumable(
    //   URL,
    //   LocalPath,
    //   {}
    // );
    // const { uri } = await downloadResumable.downloadAsync();
    // console.log("url----", uri);

    // MediaLibrary.saveToLibraryAsync(uri).then(() => {
    //   setIsLoading(false);
    //   alert("已保存到系统相册");
    // });
    let result = await FileSystem.downloadAsync(URL, LocalPath);

    //   //  the content downloaded into a folder only our app has access to.
    //   //so we will transfer this file to a publicly accessible folder.

    //   //保存
    // const cachedAsset = await MediaLibrary.createAssetAsync(result.uri);

    // const album = await MediaLibrary.getAlbumAsync("PostEvaluation");

    //   if (album == null) {
    //     console.log("进来了");
    // const createdAlumb = await MediaLibrary.createAlbumAsync(
    //   "PostEvaluation",
    //   cachedAsset,
    //   false
    // );
    //     // const nowalbum = await MediaLibrary.getAlbumAsync("PostEvaluation");

    // const assetResult = await MediaLibrary.getAssetsAsync({
    //   album: createdAlumb.id,
    //   sortBy: MediaLibrary.SortBy.creationTime,
    //   mediaType: "unknown", //importance  默认是photo类型
    // });
    //     // const asset = assetResult.assets[0];
    //     // console.log("====", asset);
    //   } else {
    //     await MediaLibrary.addAssetsToAlbumAsync([cachedAsset], album, false);
    //   }

    //   Alert.alert(
    //     "提示",
    //     `${item.fileObject.fileName}(${item.fileName})\n文件下载成功`
    //   );
    // } catch (e) {
    //   console.log("出错", e);
    //   Alert.alert("提示", "文件下载失败");
    // }
    // setIsLoading(false);

    try {
      // console.log("item------", item);
      const fileString = await FileSystem.readAsStringAsync(result.uri, {
        encoding: FileSystem.EncodingType.Base64,
      });
      // console.log("读----0", fileString);
      const permissions =
        await StorageAccessFramework.requestDirectoryPermissionsAsync();
      // console.log("-------", permissions);

      if (!permissions.granted) {
        return;
      }

      let fileName = item.fileName.split(".").shift();
      // let fileName = "test";
      // console.log(fileName);
      // console.log("geshi", item.fileObject.fileType);

      // let uft8Url = Buffer.Buffer.from(fileString, "base64").toString();
      // console.log("please----", uft8Url);
      await StorageAccessFramework.createFileAsync(
        permissions.directoryUri,
        fileName,
        // "application/pdf"
        item.fileObject.fileType
      )
        .then(async (uri) => {
          // console.log("寄哪里了");
          const result = await FileSystem.writeAsStringAsync(uri, fileString, {
            encoding: FileSystem.EncodingType.Base64,
          });
          // console.log("xie-----", result);
          alert("文件下载成功");
        })
        .catch((e) => {
          Alert.alert("提示", "文件下载失败");
          // console.log("出错kkk", e);
        });
    } catch (e) {
      console.log("出错", e);
      Alert.alert("提示", "文件下载失败");
    }
    setIsLoading(false);
  };

  const onPress = () => {
    Alert.alert("提示", "确定要下载该文件吗?", [
      {
        text: "取消",
        style: "cancel",
      },
      {
        text: "确定",
        onPress: async () => {
          await onDownload();
        },
      },
    ]);
  };

  // const onPress = async () => {
  //   const researchDir = FileSystem.documentDirectory + "postEvaluation/";
  //   const LocalPath = researchDir + item.fileObject.fileName;
  //   const URL = fileWeb + "/" + item.fileObject.filePath;

  //   // Checks if gif directory exists. If not, creates it
  //   const dirInfo = await FileSystem.getInfoAsync(researchDir);
  //   if (!dirInfo.exists) {
  //     console.log("Gif directory doesn't exist, creating...");
  //     await FileSystem.makeDirectoryAsync(researchDir, { intermediates: true });
  //   }

  //   // Downloads
  //   let result = await FileSystem.downloadAsync(URL, LocalPath);
  //   console.log("----------", result);

  //   //Returns URI to our local  file
  //   const fileInfo = await FileSystem.getInfoAsync(result.uri);
  //   console.log("--fileInfo----", fileInfo);

  //   // // Exports shareable URI - it can be shared outside your app
  //   // const shareableURI =
  //   await FileSystem.getContentUriAsync(result.uri).then((cUri) => {
  //     console.log("-----cUri", cUri);
  //     IntentLauncher.startActivityAsync("android.intent.action.VIEW", {
  //       data: cUri.uri,
  //       flags: 1,
  //       type: item.fileObject.fileType,
  //     });
  //   });
  //   // console.log("--shareableURI----", shareableURI);
  // };

  return (
    <View style={{ flexDirection: "row", marginBottom: 12 }}>
      <LoadingBar visible={isLoading} />
      {isDelete && (
        <TouchableOpacity
          style={styles.selectOption}
          onPress={() => onDeleted(item)}
        >
          {item._id === deletedId ? (
            <AntDesign name="closecircleo" size={18} color="red" />
          ) : (
            <AntDesign name="closecircleo" size={18} color="#D8D8D8" />
          )}
        </TouchableOpacity>
      )}
      <View style={{ flex: 1 }}>
        <View style={styles.container}>
          <View>
            <TouchableOpacity onPress={() => onPress()}>
              {item.fileName.split(".").pop() === "pdf" ? (
                <AntDesign name="pdffile1" size={50} color="#ccc" />
              ) : (
                <AntDesign name="wordfile1" size={50} color="#ccc" />
              )}
              <AntDesign
                style={{ position: "absolute", right: -5, bottom: -5 }}
                name="download"
                size={16}
                color="black"
              />
            </TouchableOpacity>
          </View>
          <View style={styles.cardRight}>
            <View>
              <Text style={{ fontSize: 16 }}>{item.fileName}</Text>
            </View>
            <View
              style={{
                flexDirection: "row",
                marginTop: 2,
                justifyContent: "space-between",
              }}
            >
              <View
                style={{
                  justifyContent: "center",
                }}
              >
                <Text style={{ fontSize: 14, color: "#aaa" }}>
                  {time.getFullYear() +
                    "-" +
                    (time.getMonth() + 1) +
                    "-" +
                    time.getDate() +
                    " " +
                    time.getHours() +
                    ":" +
                    time.getMinutes()}
                </Text>
              </View>

              <View
                style={[
                  styles.tag,
                  {
                    backgroundColor:
                      item.type === "pending"
                        ? "#aaa"
                        : item.type === "pass"
                        ? "#A9D67C"
                        : "#F47C68",
                  },
                ]}
              >
                <Text style={styles.tagText}>
                  {item.type === "pending"
                    ? "待审核"
                    : item.type === "pass"
                    ? "通过"
                    : "驳回"}
                </Text>
              </View>
            </View>
            {isExamine && (
              <View
                style={{
                  flexDirection: "row",
                  marginTop: 5,
                  justifyContent: "space-around",
                }}
              >
                <TouchableOpacity
                  onPress={() => onReject()}
                  style={{
                    paddingHorizontal: 10,
                  }}
                >
                  <Text>驳回</Text>
                </TouchableOpacity>
                <View style={{ width: 1, backgroundColor: "#aaa" }}></View>
                <TouchableOpacity
                  onPress={() => onPass()}
                  style={{
                    alignItems: "center",
                    paddingHorizontal: 10,
                  }}
                >
                  <Text>通过</Text>
                </TouchableOpacity>
              </View>
            )}
          </View>
        </View>
      </View>
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    backgroundColor: "#fff",
    padding: 16,
    flex: 1,
  },
  cardRight: {
    marginLeft: 10,
    flex: 1,
    justifyContent: "center",
  },
  tag: {
    backgroundColor: "#aaa",
    padding: 2,
    borderRadius: 2,
  },
  tagText: {
    color: "#fff",
    fontSize: 13,
  },
  selectOption: {
    justifyContent: "center",

    paddingRight: 5,
  },
});

export default ResearchCard;
